//
//  HomeTableViewController.swift
//  JJWeibo
//
//  Created by JJ on 15/8/31.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SVProgressHUD

private let JJStatusNormalCellID = "JJStatusNormalCellID"
private let JJStatusForwardCellID="JJStatusForwardCellID"

class HomeTableViewController: BaseTableViewController {
    
    private lazy var statusListViewModel=StatusListViewModel()
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccountViewModel.sharedUserAccount.userLogon{
            visitorLoginView?.setUpInfo(nil, message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        loadData()
        
        prepareTableView()
        
        NSNotificationCenter.defaultCenter().addObserverForName(JJStatusPictureViewSelectedPhotoNotification, object: nil, queue: nil) { (notifacation) -> Void in
            
            guard let urls=notifacation.userInfo![JJStatusPictureViewSelectedPhotoURLsKey] as?  [NSURL] else{
                return
            }
            guard let indexPath=notifacation.userInfo![JJStatusPictureViewSelectedPhotoIndexPathKey] as? NSIndexPath else{
                return
            }
            guard let picView = notifacation.object as? StatusPictureView else{
                return
            }
            
            let fromRect=picView.screenRect(indexPath)
            let toRect=picView.fullScreenRect(indexPath)
            
            let vc=PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            
            vc.transitioningDelegate = self.photoBrowserAnimator
            vc.modalPresentationStyle=UIModalPresentationStyle.Custom
            
            self.photoBrowserAnimator.prepareAnimator(picView,fromRect:fromRect, toRect: toRect, url: urls[indexPath.item])
            
            self.presentViewController(vc, animated: true, completion: nil)
            
        }
    }

    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private func prepareTableView(){
        
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: JJStatusForwardCellID)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: JJStatusNormalCellID)
        
        tableView.estimatedRowHeight=200
        tableView.rowHeight=300
        //        tableView.rowHeight=UITableViewAutomaticDimension
        tableView.separatorStyle=UITableViewCellSeparatorStyle.None
        
        refreshControl=JJRefreshControl()
        refreshControl?.addTarget(self, action:"loadData", forControlEvents:UIControlEvents.ValueChanged)
        
        tableView.tableFooterView=pullView
        
    }
    
   
    func loadData(){
        
        refreshControl?.beginRefreshing()
        statusListViewModel.loadStatus(isPullRefresh: pullView.isAnimating()).subscribeNext({ (resualt) -> Void in
            
            let count=(resualt  as! NSNumber).integerValue
            
            self.showPulldownTips(count)
            
            }, error: { (error) -> Void in
                
                self.endLoadData()
                SVProgressHUD.showInfoWithStatus("网络不行啊少年")
            }) { () -> Void in
                self.tableView.reloadData()
                self.endLoadData()
        }
        
    }
    
    private func showPulldownTips(count:Int){
        
        let title=count==0 ? "好好学习，憋刷了" :"好吧，刷到\(count)微博"
        let height:CGFloat=44
        let rect=CGRectMake(0, -2*height, UIScreen.mainScreen().bounds.width, height)
        
        pullDownTipLable.text=title
        pullDownTipLable.frame=rect
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            self.pullDownTipLable.frame=CGRectOffset(rect, 0, 3 * height)
            
            }) { (_) -> Void in
               UIView.animateWithDuration(1.0, delay: 0.5, options: [], animations: { () -> Void in
                self.pullDownTipLable.frame=rect
                }, completion: { (_) -> Void in
                    
               })
        }
        
    }
    private lazy var pullDownTipLable:UILabel = {
        let lable=UILabel(title: nil, color: UIColor.whiteColor(), fontsize: 18)
        lable.backgroundColor=UIColor.orangeColor()
        lable.textAlignment=NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(lable, atIndex: 0)
        
        return lable
        }()
    
   private func endLoadData(){
        pullView.stopAnimating()
        self.refreshControl?.endRefreshing()
    }
    private lazy var pullView:UIActivityIndicatorView = {
       
        let indicator=UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color=UIColor.darkGrayColor()
        return indicator
        
    }()
    
}

extension HomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.status.count ?? 0
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let statusViewModel=statusListViewModel.status[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(statusViewModel.cellID, forIndexPath: indexPath) as! StatusCell
        
        cell.statusViewModel = statusViewModel
        
        if indexPath.row == (statusListViewModel.status.count - 1) && !pullView.isAnimating(){
            pullView.startAnimating()
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let viewModel=statusListViewModel.status[indexPath.row]
        if viewModel.rowheight>0{
            
            return viewModel.rowheight
        }
        let cell=tableView.dequeueReusableCellWithIdentifier(viewModel.cellID) as! StatusCell
        viewModel.rowheight=cell.rowHeight(viewModel)
        return viewModel.rowheight
    }

}